package com.bawei.contentresolver;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.content.ContentResolver;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.provider.ContactsContract;
import android.util.Log;

public class MainActivity extends AppCompatActivity {
    private Uri uri;
    private ContentResolver contentResolver;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //通过contentResovler查询数据
        uri = Uri.parse("content://com.bawei.2010");
        contentResolver = getContentResolver();
        query();

    }
    @SuppressLint("Range")
    private void query() {
        //注册观察者只要provider内容发生改变，重新查询
        contentResolver.registerContentObserver(uri, true, new ContentObserver(new Handler()) {
            @Override
            public void onChange(boolean selfChange) {
                super.onChange(selfChange);
                //查询全部
                Cursor cursor = contentResolver.query(uri, null, null, null, null);
                if(cursor != null){
                    while (cursor.moveToNext()){
                        int id = cursor.getInt(cursor.getColumnIndex("_id"));
                        String name = cursor.getString(cursor.getColumnIndex("name"));
                        int age = cursor.getInt(cursor.getColumnIndex("age"));
                        Log.d("ytx", "query: "+id+"-"+name+"-"+age);
                    }
                }
            }
        });



    }

    /**
     * 获得手机中的联系人
     */
    @SuppressLint("Range")
    private void queryContract(){
        Cursor cursor = contentResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
        if(cursor != null){
            while (cursor.moveToNext()){
                String name=cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
                String number=cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                Log.d("ytx", "query: "+name+"-"+number);
            }
        }

    }
}